var center=0;

//呼叫模型
var ServIP;				//服务器ip
var deviceId;			//分机号码
var agentId;			//服务器ip
var queue;				//登录队列
var password;			//登录密码
var callId;				//呼叫id
var caller;				//主叫
var called;				//被叫;
var filename;			//录音文件
var startTime;			//通话开始时间	暂时不用，做到后台去
var endTime;			//通话结束时间	暂时不用，做到后台去
$(function(){
	//alert("OK");
})
	
	function getEl(id){
	  return document.getElementById(id);
	}
	function printMsg(msg){
	  getEl('msgs').value=msg+"\r\n"+getEl('msgs').value;
	}
	
	
	
//1.环境初始化的事件	
	function OnInService(){
	  printMsg("[OnInService]");
//	  alert("初始化环境成功");
	}	
	function OnOutOfService(exitcode){
	  printMsg("[OnOutOfService]exitcode:"+exitcode);
//	  alert("控件环境被意外关闭");
	}	
	function AgentLoggedOn(cause,dev,agent,pw,queue){
		 printMsg("[AgentLoggedOn]dev:"+dev+",agent:"+agent+",pw:"+pw+",queue:"+queue);
	}	
	function AgentLoggedOff(cause,dev,agent,pw,queue){
		callId = null;
		caller = null;
		called = new Array();
		filename=null;
		startTime = null;
		endTime = null;
		 printMsg("[AgentLoggedOff]dev:"+dev+",agent:"+agent+",pw:"+pw+",queue:"+queue);
	}
	
	function AgentReady(cause,dev,agent,pw,queue){
		 printMsg("[AgentReady]dev:"+dev+",agent:"+agent+",pw:"+pw+",queue:"+queue);
	}
    function NotReady(){
    	var ret=RTsapiBar.SetAgentState("",2,0);
    	printMsg("[NotReady]Result:"+ret);
    }
	function AgentNotReady(cause,dev,agent,pw,queue){
		 printMsg("[AgentNotReady]dev:"+dev+",agent:"+agent+",pw:"+pw+",queue:"+queue);
	}
	
	
	
//2.通话的函数
	function makeCall(number)
	{
		var ret=RTsapiBar.MakeCall("",number,"",0,"");
		printMsg("[MakeCall]Result:"+ret);
	}
	function addMultiParty(devs)
	{
	//	alert("电话号码: devs:"+devs);
		var ret = RTsapiBar.AddMultiParty(devs);
		printMsg("[AddMultiParty]Result:"+ret);
	}
	
	//后台发送传真
	function AddFaxTask(taskid,callid,filename){
		//alert("后台发送传真=="+"taskid:"+taskid+"callid:"+callid+"filename:"+filename);
		//var ret=RTsapiBar.AddFaxSenderTask(1039,"3081","20100429162542_li_772.tif");
		var ret=RTsapiBar.AddFaxSenderTask(taskid,callid,filename);
		if(ret=="0"){      //参考操作文档，不同返回值代表不同问题
			alert("发送成功！");
		}else alert("发送失败！");
    }
	
//3.通话过程的事件	
	function AgentBusy(cause,dev,agent,pw,queAgentNotReadyue){
		printMsg("[AgentBusy]dev:"+dev+",agent:"+agent+",pw:"+pw+",queue:"+queue);
	}
	function Originated(callid,caller,called,reason,localstate,data)
	{
		 printMsg("[Originated]callid:"+callid+",caller:"+caller+",called:"+called+",reason:"+reason+",localstate:"+localstate+",data:"+data);
	}
	function Delivered(callid,caller,called,alerting,reason,localstate,data)
	{
		 printMsg("[Delivered]callid:"+callid+",caller:"+caller+",called:"+called+",alerting:"+alerting+",reason:"+reason+",localstate:"+localstate+",data:"+data);
	}
	//判断是打进来的电话，定是打出去的电话
	function Established(callid,Caller,Called,answer,reason,localstate,data)
	{
		printMsg("[Established]callid:"+callid+",caller:"+caller+",called:"+Called+",answer:"+answer+",reason:"+reason+",localstate:"+localstate+",data:"+data);
		callId = callid;
		caller = Caller;
		called[called.length]=Called;
		
		//这里是打进来的电话，要弹屏幕
		if(Called==deviceId)
		{
			$('#tabFrame', window.parent.parent.parent.frames['mainFrame'].document).attr("src","wzp/event_accept.jsp");
			$('#rightFrame', window.parent.parent.parent.frames['mainFrame'].document).hide("slow");
			$('#tabFrame', window.parent.parent.parent.frames['mainFrame'].document).show("slow");
//			window.open("/ag/lwc/EventAcceptCallAction.action?number="+Caller,"newwindow",'height='+screen.height-100+',width='+screen.width-200+',top=10,left=0,toolbar=no,menubar=no,scrollbars=yes, resizable=yes,location=no, status=no')
		}
		
		//显示通话信息
		if(deviceId == Called)		//证明是外线打进来,或者是两方通话
		{
				var dia=$(parent.window.frames['main'].document).find("#msgdialog");
				$("<p>已经和"+caller+"建立通话 <span>0</span>:<span>0</span></p>").appendTo(dia);
			//	dia.dialog("open");			
		}
		else
		{
			var p=$(parent.window.frames['main'].document).find("#"+Called)
			p.text(p.attr("name")+"   ("+Called+")已经建立通话  ").append("<span>0</span>").append(": ").append("<span>0</span>");
			
		}
	}
	//收取录音文件
	function PrivateMsg(eventid,msg)
	{
		printMsg("[PrivateMsg]eventid:"+eventid+",msg:"+msg);
		if(eventid==10008)						//录音
		{	
			var a = msg.split(";");
			filename = a[2].split("=")[1];
			var url="/ag/lwc/establishTimeAction.action";
			var req ={};
			var ajax=jQuery.post(url,req,function (data){					
					if((typeof data.message) == "undefined")
							data = eval("("+data+")");
					//alert(data.message);
					if(data.message=="startTime"){
					//	alert("录音开始");
					}
				});
		}
	}
	function ConnectionCleared(callid,deviceid,reason,localstate,data)
	{
		printMsg("[ConnectionCleared]callid:"+callid+",deviceid:"+deviceid+",reason:"+reason+",localstate:"+localstate+",data:"+data);
		
		if(localstate==0){	//
		torecord();
		}
	}
	//通话结束，保存通话日志，清空呼叫模型	
	function AgentWorkReady(cause,dev,agent,pw,queue){
		printMsg("[AgentWorkReady]dev:"+dev+",agent:"+agent+",pw:"+pw+",queue:"+queue);
//		var devs = called.join(",");			//被叫字符串
//		var tapeUrl = "http://172.17.7.177/vasptools/service/v1/filemanager/download?file="+filename+"&type=userrec";
//		
//		$("#tapeRecord",window.parent.parent.frames['tabFrame'].document).text(tapeUrl);
//		
//		if(confirm("是否下载录音 ？")){s			//下载录音
//			$('#rightFrame', window.parent.parent.parent.frames['mainFrame'].document).hide("slow");
//			$('#tabFrame', window.parent.parent.parent.frames['mainFrame'].document).show("slow");
//			$('#tabFrame',window.parent.parent.parent.frames['mainFrame'].document).attr("src","http://172.17.7.177/vasptools/service/v1/filemanager/download?file="+filename+"&type=userrec");
//		}
//		
//		var url="/ag/lwc/SaveCallLogAction.action";
//		var req={caller:caller,called:devs,filename:filename};
//		var ajax=jQuery.post(url,req,function (data){
//				
//				if((typeof data.message) == "undefined")
//						data = eval("("+data+")");
//				//alert(data.message);
//				if(data.message=="saveContactLogSuccess"){
//				//	alert("保存日志成功");
//				}
//			});
//	//清空呼叫模型	
//		callId = null;
//		caller = null;
//		called = new Array();
//		filename=null;
//		startTime = null;
//		endTime = null;
	}
	
	/**
	 * 用来复用
	 * @param filename
	 * @return
	 */
	function torecord(){
			var devs = called.join(",");		//被叫字符串
		var tapeUrl = "http://172.17.7.177/vasptools/service/v1/filemanager/download?file="+filename+"&type=userrec";
		
		$("#tapeRecord",window.parent.parent.frames['tabFrame'].document).text(tapeUrl);
//		
		if(confirm("是否下载录音? ？")){			//下载录音
			$('#rightFrame', window.parent.parent.parent.frames['mainFrame'].document).hide("slow");
			$('#tabFrame', window.parent.parent.parent.frames['mainFrame'].document).show("slow");
			$('#tabFrame',window.parent.parent.parent.frames['mainFrame'].document).attr("src","http://172.17.7.177/vasptools/service/v1/filemanager/download?file="+filename+"&type=userrec");
		}
		
		var url="/ag/lwc/SaveCallLogAction.action";
		var req={caller:caller,called:devs,filename:filename};
		var ajax=jQuery.post(url,req,function (data){
				
				if((typeof data.message) == "undefined")
						data = eval("("+data+")");
				//alert(data.message);
				if(data.message=="saveContactLogSuccess"){
				//	alert("保存日志成功");
				}
			});
	//清空呼叫模型	
		callId = null;
		caller = null;
		called = new Array();
//		filename=null;
		startTime = null;
		endTime = null;
	}
	function TransferConference(calling,user,callid,otherCallid){
		printMsg("[TransferConference]calling:"+calling+",user:"+user+",callid:"+callid+",otherCallid:"+otherCallid);
	}

	//加入会议，更改callid
	function TransferToConference(calling,user,callid,otherCallid){
		printMsg("[TransferToConference]calling:"+calling+",user:"+user+",callid:"+callid+",otherCallid:"+otherCallid);
		callId = callid;
	}
	//清空呼叫模型
	function CallCleared(callid,deviceid,reason,localstate,data)
	{
//		callId = null;
//		caller = null;
//		called = new Array();
//		filename=null;
//		startTime = null;
//		endTime = null;
		printMsg("[CallCleared]callid:"+callid+",deviceid:"+deviceid+",reason:"+reason+",localstate:"+localstate+",data:"+data);
	}
	function Failed(callid,caller,called,failed,reason,localstate,data)
    {
    	printMsg("[Failed]callid:"+callid+",caller:"+caller+",called:"+called+",failed:"+failed+",reason:"+reason+",localstate:"+localstate+",data:"+data);
    }
	

	
	
//4.启动环境
	function onInit(){
	
	//  4-1.注册事件
	
		RTsapiBar.attachEvent('InService',OnInService);												
		RTsapiBar.attachEvent('OutOfService',OnOutOfService); 									
		RTsapiBar.attachEvent('AgentLoggedOn',AgentLoggedOn);   							
		RTsapiBar.attachEvent('AgentLoggedOff',AgentLoggedOff);   						
		RTsapiBar.attachEvent('AgentReady',AgentReady);   										
		RTsapiBar.attachEvent('AgentNotReady',AgentNotReady);  										 							
		RTsapiBar.attachEvent('AgentWorkNotReady',AgentWorkNotReady);

		RTsapiBar.attachEvent('AgentBusy',AgentBusy);
		RTsapiBar.attachEvent('Originated',Originated);   										
		RTsapiBar.attachEvent('Delivered',Delivered);   											
		RTsapiBar.attachEvent('Established',Established);
		RTsapiBar.attachEvent('PrivateMsg',PrivateMsg);	
		RTsapiBar.attachEvent('ConnectionCleared',ConnectionCleared);
		RTsapiBar.attachEvent('AgentWorkReady',AgentWorkReady);
		RTsapiBar.attachEvent('TransferConference',TransferConference);
		RTsapiBar.attachEvent('TransferToConference',TransferToConference);
		RTsapiBar.attachEvent('Failed',Failed); 															
		RTsapiBar.attachEvent('CallCleared',CallCleared); 											
		RTsapiBar.attachEvent('Diverted',Diverted); 														
					
		RTsapiBar.attachEvent('UserState',UserState);
		RTsapiBar.attachEvent('GetAgents',GetAgents);
		RTsapiBar.attachEvent('Retrieved',Retrieved);
		RTsapiBar.attachEvent('Conferenced',Conferenced);
		RTsapiBar.attachEvent('CallChanged',CallChanged); 
		RTsapiBar.attachEvent('PrivateMsgEx',PrivateMsgEx);
		
		ServIP = $.trim($("#ServIP").val());
		deviceId = $.trim($("#deviceId").val());
		agentId = $.trim($("#AgentID").val());
		queue = $.trim($("#queue").val());
		password = $.trim($("#password").val());
	//	alert("ServIP :"+ServIP+"\ndeviceId:"+deviceId+"\nagentId:"+agentId+"\nqueue:"+queue+"\npassword:"+password+"\nagentId.length"+agentId.length);
	
	 //4-2.若用户对应一个坐席,就开启控件环境,初始化呼叫模型
		if(agentId.length>0&&ServIP.length>0&&deviceId.length>0&&queue.length>0)
		{
				RTsapiBar.SetCTIServer(ServIP);		
				RTsapiBar.SetLocalDevice(deviceId);			
				RTsapiBar.SetAgent(agentId,password);
				RTsapiBar.SetQueue(queue);
	
				called = new Array();
			//	启动控件环境
				RTsapiBar.CreateCTIEnv();
				RTsapiBar.SetAgentState(queue,0,0);			
				setTimeout(function(){RTsapiBar.SetAgentState(queue,3,0);},"1000");
		}

	}
	
	//5.其它事件
	
	function Retrieved(callid,deviceid,reason,localstate)
	{
	 
	}
	function Conferenced(oldcallid,newcallid,adddeviceid,reason,localstate,data)
	{
	//	printMsg("[Conferenced]oldcallid:"+oldcallid+",newcallid:"+newcallid+",adddeviceid:"+adddeviceid+",reason:"+reason+",localstate:"+localstate+",data:"+data);
	}
	
	function AgentWorkNotReady(cause,dev,agent,pw,queue){
		
	}
    function Diverted(callid,caller,called,dest,reason,localstate,data)
    {
    	printMsg("[Diverted]callid:"+callid+",caller:"+caller+",called:"+called+",dest:"+dest+",reason:"+reason+",localstate:"+localstate+",data:"+data);
    }
	
	function GetAgents(agentstate,agentid,deviceid)
	{
		printMsg("[GetAgents]agentid:"+agentid+",deviceid:"+deviceid+",agentstate:"+agentstate);
	}
	
	function GetFaxSenderTask(state,taskid,agentid,deviceid,faxname,trycount,end)
	{
		
	}
	function CallChanged(calls)
	{
	
	}

	function UserState(user,callid,state){
	       
		}
	function PrivateMsgEx(eventid,data){
	
		}
	
	
	
	//6.测试函数
    function CreateEnv(){
    	var ret=RTsapiBar.CreateCTIEnv();				
    	printMsg("[CreateEnv]Result:"+ret);
    }
    	
    function CloseEnv(){
    	var ret=RTsapiBar.CloseCTIEnv();				
    	printMsg("[CloseEnv]Result:"+ret);
    }  


 	function SetServ(){
		if(getEl('op_servip').value.length>0){
    		var ret=RTsapiBar.SetCTIServer(getEl('op_servip').value);	
    		printMsg("[SetServ]Result:"+ret);
    	}
    }
	$("#makeCall").click(function(){
		 var number = $("#dev").val();
		alert("电话号码: "+number);
		//	RTsapiBar.MakeCall("",number,"",0,"");
		
		});
	$("#party").click(function(){
		 var numbers = $("#devs").val();
		alert("电话号码: "+numbers);
		//	var ret=RTsapiBar.AddMultiParty(numbers);
		
		});	
	function Test(){
		RTsapiBar.Test("123456");
	}
